package com.klxedu.ms.gateway.security.filter;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.StringUtils;

import com.klxedu.ms.gateway.event.EventSender;
import com.klxedu.ms.gateway.event.LoginEvent;
import com.klxedu.ms.gateway.security.authentication.CustomUserDatails;
import com.klxedu.ms.gateway.security.authentication.IAuthenticatedUser;
import com.klxedu.ms.gateway.utils.SpringBeanUtils;

public class CustomBasicAuthenticationFilter extends BasicAuthenticationFilter {

	private Log logger = LogFactory.getLog(this.getClass());
	
	public CustomBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
		super(authenticationManager);
	}

	public CustomBasicAuthenticationFilter(AuthenticationManager authenticationManager,
			AuthenticationEntryPoint authenticationEntryPoint) {
		super(authenticationManager, authenticationEntryPoint);
	}

	@Override
	protected void onSuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
			Authentication authResult) throws IOException {
		String client = request.getParameter("client");
		CustomUserDatails principal = (CustomUserDatails) authResult.getPrincipal();
		if (StringUtils.isEmpty(client)) {
			client = "pc";
		}
		principal.setClient(client);
		
		IAuthenticatedUser extendAccountInfo = (IAuthenticatedUser) principal.getExtendAccountInfo();
		//发送登录成功事件
		LoginEvent event = new LoginEvent(request, client);
		event.setUserID(extendAccountInfo.getEntityID());
		event.setLoginID(extendAccountInfo.getLoginID());
		event.setEventType(LoginEvent.EVENT_TYPE_LOGIN);
		SpringBeanUtils.getBean(EventSender.class).send(event);
		//激活账号
//		IAuthenticatedUser extendAccountInfo = (IAuthenticatedUser) principal.getExtendAccountInfo();
//		if(extendAccountInfo.getState() == LoginUser.STATE_NOTACTIVE) {
//			try {
//				UserFeignClient userFeignClient = SpringBeanUtils.getBean(UserFeignClient.class);
//				userFeignClient.updateAccountState(new String[] { extendAccountInfo.getAccountID() }, LoginUser.STATE_ON);
//			} catch (Exception e) {
//				logger.error("激活账号["+extendAccountInfo.getLoginID()+"]失败", e);
//			}
//		}
	}

}
